import { tts } from '@/service/share'

export const processTextToSpeech = async (text: string, onComplete?: () => void) => {
  let audioText = text
  const punc = ['。', '.', '？', '?', '；', ';', '，', ',']

  const playAudio = (audioBuffer: ArrayBuffer) => {
    return new Promise<void>((resolve) => {
      const audioBlob = new Blob([audioBuffer], { type: 'audio/wav' })
      const audioUrl = URL.createObjectURL(audioBlob)
      const audio = new Audio(audioUrl)

      audio.addEventListener('ended', () => {
        URL.revokeObjectURL(audioUrl) // 释放 URL
        resolve() // 语音播放完成
      })

      audio.play().catch((e) => {
        console.error('音频播放失败:', e)
        resolve() // 即使失败，也继续流程
      })
    })
  }

  // 切分文本并依次处理
  const parts: string[] = []
  while (audioText) {
    let lastPuncIndex = -1
    for (const element of punc) {
      const index = audioText.lastIndexOf(element)
      if (index > lastPuncIndex)
        lastPuncIndex = index
    }

    if (lastPuncIndex !== -1) {
      const firstPart = audioText.slice(0, lastPuncIndex + 1)
      audioText = audioText.slice(lastPuncIndex + 1)
      parts.push(firstPart)
    }
    else {
      break
    }
  }

  // 依次请求 TTS 并播放
  for (const part of parts) {
    try {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-expect-error
      const data: ArrayBuffer = await tts(part)
      await playAudio(data) // 等待当前音频播放完成
    }
    catch (error) {
      console.error('TTS 处理失败:', error)
    }
  }

  // 全部播放完成后，触发 onComplete
  if (onComplete)
    onComplete()
}
